package com.dora.http.base.headerfilter;

import com.dora.http.requestbuilder.RequestHttpBuilder;
import com.dora.http.utils.JSONSerializer;
import io.restassured.filter.Filter;
import io.restassured.filter.FilterContext;
import io.restassured.http.Headers;
import io.restassured.response.Response;
import io.restassured.specification.FilterableRequestSpecification;
import io.restassured.specification.FilterableResponseSpecification;
import lombok.extern.slf4j.Slf4j;

import java.util.List;
import java.util.Map;

/**
 * @Author: Dora
 * @Description: 打印请求响应
 * @Date: 2021/12/14
 */
@Slf4j
public class RequestResLogFilter implements Filter {
    @Override
    public Response filter(FilterableRequestSpecification requestSpec, FilterableResponseSpecification responseSpec, FilterContext ctx) {
        Response response = ctx.next(requestSpec, responseSpec);

        String url = requestSpec.getURI();
        String method = requestSpec.getMethod();
        Headers headers = requestSpec.getHeaders();

        Map reqFormParams =  requestSpec.getFormParams();
        String requestsStr = reqFormParams != null && reqFormParams.size() > 0 ? JSONSerializer.serialize(reqFormParams)
                : JSONSerializer.serialize(requestSpec.getBody());
        String responseStr = response.asString();
        List responseHeaders = response.getHeaders().asList();

        log.info("\n#################################### Request ALL ####################################\n" +
                "|### → URL : " + url + "\n" +
                "|### → HTTP_METHOD : " + method + "\n" +
                "|### → HTTP_HEADER : " + headers.asList() + "\n" +
                "|### → Request : {" + requestsStr + "}\n" +
                "################################################################# Request Done #################################################################\n" +
                "|### → Response Header: {" + responseHeaders + "}\n" +
                "|### → Response Body : {" + responseStr + "}\n" +
                "################################################################# Response Done #################################################################\n");
        return response;
    }
}
